const fs = require('fs');
const path = require('path');
const { organizeData } = require('./data和props转换.js')
const {organizeStyles} = require("./整理 less");

const folderPath = './源文件/index.js'
setFile(folderPath)

function setFile (path) {
  fs.readFile(`./${path}`, 'utf8', async (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    data += '666666666666666666'
    data = data.replace(/this.\$t/g, '$t');
    data = data.replace(/i18n.t\('([\s\S]*?)'\)/g, (_, a) => {
      return `$t('${a}')`
    });
    //
    // data = data.replace(new RegExp(/\$\{this.\$t\('(\w*).(\w*)'\)}/, 'g'), (_,a,b,c,d) => {
    //   return `${zh[a][b]}`
    // });
    // data = data.replace(new RegExp(/this.\$t\('(\w*).(\w*)'\)/, 'g'), (_,a,b) => {
    //   return `'${zh[a][b]}'`
    // });

    const organizeDataRef = await organizeData(data)

    const dataList = organizeDataRef.data.list
    const props = organizeDataRef.props.list

    data = data.replace('666666666666666666', '')

    // 修改 data
    for (let i = 0; i < dataList.length; i++) {
      const item = dataList[i]
      data = data.replace(new RegExp(`\\bthis\\.(${item})(?![\\w\\r\\n])`, 'g'), '$1.value');
      data = data.replace(new RegExp(`\\bthis\\.(${item})\\.(\\w+)`, 'g'), '$1.value.$2');
      data = data.replace(new RegExp(`return\\s+this\\.(${item})\\b`, 'g'), 'return $1.value');
      data = data.replace(new RegExp(`this.${item}\\s`, 'g'), (_,v) => {
        return `${item}.value`
      });
    }

    // 修改 props
    for (let i = 0; i < props.length; i++) {
      const row = props[i]
      data = data.replace(new RegExp(`\\bthis\\.(${row})(?![\\w\\r\\n])`, 'g'), `props.value.$1`);
      data = data.replace(new RegExp(`\\bthis\\.(${row})\\.(\\w+)`, 'g'), `props.value.$1.$2`);
      data = data.replace(new RegExp(`return\\s+this\\.(${row})\\b`, 'g'), 'return props.value.$1');
    }
    // // 替换其他内容
    const emitList = []
    data = data.replace(/this\.?\$emit\('([^']*)'/g, (_,name) =>{
      emitList.push(name)
      return _
    });
    data = data.replace(new RegExp('this.\\$emit', 'g'), 'emit');
    data = data.replace(new RegExp('this.\\$nextTick', 'g'), 'nextTick');
    data = data.replace(new RegExp('this.\\$message', 'g'), 'ElMessage');
    data = data.replace(new RegExp('this.\\$sdk', 'g'), 'hyRtcSdkStore');
    data = data.replace(new RegExp('this.\\$business', 'g'), 'hyRtcBusinessStore');
    //
    // // 修改 this.$set
    data = data.replace(/this\.\$set\(([^,]+),\s*'([^']+)'\s*,\s*([^)]+)\)/g, '$1.$2 = $3');
    data = data.replace(/this\.\$set\(([^,]+),\s*([^,]+),\s*([^)]+)\)/g, '$1[$2] = $3');
    // 修改 this.mainStore
    data = data.replace(/this\.mainStore\.commit\('([^']+)',\s*([^)]+)\)/g, (_,A,B) => {
      if (!A.includes('/')) {
        return `mainCommunicationStore.${A}(${B})`
      }
      return _
    });
    data = data.replace(/this\.mainStore\.commit\('([^\/]+)'\)/g, (_,A) => {
      return `mainCommunicationStore.${A}()`
    });
    data = data.replace(/this\.mainStore\.commit\('([^\/]+)\/([^']+)',\s*([^)]+)\)/g, 'mainCommunicationStore.$1(\'$2\', $3)');

    // this.$store
    data = data.replace(/this\.\$store\.commit\('([^']+)',\s*([^)]+)\)/g, (_,A,B) => {
      if (!A.includes('/')) {
        return `projectCommunication.${A}(${B})`
      }
      return _
    });
    data = data.replace(/this\.\$store\.commit\('([^\/]+)'\)/g, (_,A) => {
      return `projectCommunication.${A}()`
    });
    data = data.replace(/this\.\$store\.commit\('([^\/]+)\/([^']+)',\s*([^)]+)\)/g, 'projectCommunication.$1(\'$2\', $3)');
    // 将 this. 移除
    data = data.replace(new RegExp(`\\bthis\\.(?!mainStore\\b|\\$sdk\\b)(\\w+)\\b`, 'g'), '$1');

    // 设置 deleteConfirmationBox
    data = data.replace(/this\.\$deleteConfirmationBox\(([\s\S]*?)}(,|\))/g, (match, value) => {
      match = match.replace(/deleteTitle/g,'tipsTitle')
      match = match.replace(/deleteContent/g,'tipsContent')
      match = match.replace(/submitText/g,'submitBtnText')
      match = match.replace(/closeText/g,'closeBtnText')
      match = match.replace(/deleteTitle/g,'tipsTitle')
      match = match.replace(/tipsTitleImg/g,'tipsTitleIcon')
      match = match.replace(/tipsTitleIcon: 'tips'/g,`tipsTitleIcon: 'sys-button-tips',tipsTitleIconClass: 'text-hy-text-main'`)
      match = match.replace('this.$deleteConfirmationBox','HyTipsModal')
      return match
    })
    data = data.replace(/closeClass: '(\w*)'/g, (match, value) => {
      let text = ''
      if (value === 'button_default') {
        text = 'default'
      } else if (value === 'button_addTo') {
        text = 'success'
      } else if (value === 'button_delete') {
        text = 'danger'
      }
      return `closeBtnType: ${text}`
    })
    data = data.replace(/submitClass: '(\w*)'/g, (match, value) => {
      let text = ''
      if (value === 'button_default') {
        text = 'default'
      } else if (value === 'button_addTo') {
        text = 'success'
      } else if (value === 'button_delete') {
        text = 'danger'
      }
      return `submitBtnType: '${text}'`
    })

    // 设置组件ref
    const componentsList = []
    const setComponentsList = (name) => {
      const index = componentsList.findIndex(v => v === name)
      if (index === -1) {
        componentsList.push(name)
      }
    }
    data = data.replace(/this\.\$refs.(\w*)(.?)/g, (match, value, a) => {
      setComponentsList(value + 'Ref')
      if (match.includes(')')) {
        return `${value}Ref.value)`
      }
      if (a === '.') {
        return `${value}Ref.value?.`
      } else {
        return `${value}Ref.value`
      }
    })

    data = data.replace(new RegExp(`window.sessionStorage.getItem`, 'g'), 'sessionCache.getCache');
    data = data.replace(new RegExp(`window.sessionStorage.casesType`, 'g'), 'sessionCache.setCache');
    data = data.replace(new RegExp(`AppTableRef.value\\?.getData`, 'g'), 'AppTableRef.value?.getTableData');
    data = data.replace(new RegExp(`AppTableRef.value\\?.setSelectedList`, 'g'), 'AppTableRef.value?.setSelectedData');
    data = data.replace(new RegExp(`AppTableRef.value\\?.clearSelectedList`, 'g'), 'AppTableRef.value?.clearSelection');

    let componentsData = ''
    let functionName = ''
    componentsList.forEach((item) => {
      functionName += `${item},`
      componentsData += `
        const ${item} = ref(null)`
    })
    organizeDataRef.data.list.forEach((item) => {
      functionName += `${item},`
    })

    fs.writeFile('./结果文件/函数名称.ts', `${functionName}`, 'utf8', (err) => {
      if (err) {
        console.error(err);
        return;
      }
    });
    // fs.writeFile('./结果文件/index.ts', ``, 'utf8', (err) => {
    //   if (err) {
    //     console.error(err);
    //     return;
    //   }
    // });
    fs.writeFile('./结果文件/index.ts', `
    import { nextTick, ref } from 'vue'
    import { $t } from '@/hooks/use-i18n'
    import { ElMessage } from 'element-plus'
    import type { InitParams } from '@/model/index-model'
    ${data.includes('HyTipsModal') ? `import { HyTipsModal } from 'command-center-v3-common'` :''}
    
    const emit = defineEmits(${JSON.stringify(emitList)})
    ${organizeDataRef.props.code}
     ${organizeDataRef.data.code}
    export function use(initParams?: InitParams) {
      const emit = initParams.emit
      const props = ref< Props >(initParams.props || {})
${componentsData}
${organizeDataRef.data.values}
    }

    ${data}
    `, 'utf8', (err) => {
      if (err) {
        console.error(err);
        return;
      }
    });
  });
}
